<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" th:href="@{/layui/css/layui.css}"/>
    <link rel="stylesheet" th:href="@{/css/frm_base.css}" />
    <script th:src="@{/js/jquery-3.5.1.js}"></script>
    <style>
        .tree{
            padding: 10px 20px;
        }
        .nav_top{
            padding: 20px 20px 10px 20px;
        }
        
        #title{
            border-bottom: 1px solid rgb(230,230,230);
            padding: 13px 0;
            text-align: center;
            color: #606266;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
<div class="main">

    <div class="layui-row">
        <div class="layui-col-md2 tree">
            <div id="treeDiv">
                <div id="title" style="">班级列表</div>
                <div id="academyTree"></div>
            </div>
            
        </div>
        <div class="layui-col-md10">
            <div class="nav_top">
                <span class="layui-breadcrumb">
                  <a href="javaScript:void(0);" class="nav1"></a>
                  <a href="javaScript:void(0);" class="nav2"></a>
                  <a><cite class="nav3"></cite></a>
                </span>
            </div>
            <hr class="layui-bg-green">
            <div class="container head">
                <form action="" class="layui-form" id="searchForm">
                    <div class="layui-form-item">
                        <div class="layui-input-inline">
                            <input type="text" name="courseName" autocomplete="off" placeholder="考试课程名称" class="layui-input">
                        </div>
                        <div class="layui-input-inline">
                            <input type="text" name="address" autocomplete="off" placeholder="考试地点" class="layui-input">
                        </div>
                        <div class="layui-input-inline">
                            <input type="text" name="examDate" id="searchDate" autocomplete="off" placeholder="考试时间" class="layui-input">
                        </div>
                        <div class="layui-form-inline">
                            <button class="layui-btn" lay-submit lay-filter="searchBtn">搜索</button>
                            <button class="layui-btn layui-btn-normal" type="button" id="addBtn">添加</button>
                        </div>
                    </div>
                </form>
                <!--<button class="layui-btn layui-btn-normal" type="button" id="addBtn">添加</button>-->
            </div>
            <div class="container content">
                <table class="layui-hide" id="exam" lay-filter="exam"></table>
            </div>
        </div>
    </div>
</div>

<script type="text/html" id="toolbar">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm layui-btn-primary" lay-event="edit">编辑</button>
        <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="remove">删除</button>
    </div>
</script>

<script type="text/html" id="dialogHtml">
    <div id="dialog">
        <form action="" class="layui-form" lay-filter="dialog-form">
            <input type="hidden" name="id">
            <div class="layui-form-item">
                <label class="layui-form-label">班级</label>
                <div class="layui-input-block">
                    <select name="clazzId" id="clazz" lay-verify="required" lay-filter="clazz"></select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">科目</label>
                <div class="layui-input-block">
                    <select name="courseId" id="course" lay-verify="required" lay-filter="course"></select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">地点</label>
                <div class="layui-input-block">
                    <input type="text" name="address" lay-verify="required" autocomplete="off" placeholder="请输考试地点" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">日期</label>
                <div class="layui-input-block">
                    <input type="text" name="examDate" id="examDate" lay-verify="required" autocomplete="off" placeholder="请输考试日期" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">开始时间</label>
                <div class="layui-input-block">
                    <input type="text" name="startTime" id="startTime" lay-verify="required" autocomplete="off" placeholder="请输考试开始时间" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">结束时间</label>
                <div class="layui-input-block">
                    <input type="text" name="endTime" id="endTime" lay-verify="required" autocomplete="off" placeholder="请输考试结束时间" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item" style="display: none">
                <div class="layui-input-block">
                    <button type="submit" class="layui-btn" lay-submit lay-filter="dialogBtn" id="dialogBtn">提交</button>
                </div>
            </div>
        </form>
    </div>
</script>

<script th:src="@{/layui/layui.js}"></script>
<script th:inline="none">

    $.fn.serializeObject = function(){
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    }


    layui.use(['element', 'layer', 'form', 'table','tree','laydate'], function () {
        var form = layui.form,
            layer = layui.layer,
            tree = layui.tree,
            laydate = layui.laydate,
            table = layui.table;

        var flag = 'add';
        var isFirst = true;
        // 保存在页面上点击的树型列表中的专业
        var clazzId = undefined;
        var subjectId = 0;
        var clazzArr = [];
        var courseArr = [];
        var treeArr = []

        getTree()
        // initTable()

        $('#addBtn').click(function () {
            flag = 'add';
            showDialog();
        })

        laydate.render({
            elem: '#searchDate',
            format: 'yyyy-MM-dd',
        });

        // 搜索提交
        form.on('submit(searchBtn)', function (data) {
            search(data.field) // data.field是一个js对象
            return false;
        })

        // 新增提交
        form.on('submit(dialogBtn)', function (data) {
            var formData = data.field;
            formData.sbjId = subjectId
            console.log(formData)
            update(formData, flag)
            return false;
        })

        //监听工具条
        table.on('tool(exam)', function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event;
            console.log(data)
            if (layEvent === 'remove') { //删除
                layer.confirm('真的删除？', function (index) {
                    remove(data);
                });
            } else if (layEvent === 'edit') { //编辑
                flag = 'edit';
                showDialog(data);
            }
        });

        function getTree() {
            $.get("/ssms/academy/academyTree2",function (res) {
                if(res.code == 200){
                    treeArr = res.data;
                    tree.render({
                        elem: '#academyTree'  //绑定元素
                        ,accordion:true
                        ,data:treeArr
                        ,click: function(obj){
                            if(obj.data.field == 'clazz'){ // 没有子节点时，表示当前是专业节点
                                var clazz = obj.data //得到当前点击的节点数据
                                clazzId = clazz.id;
                                if(isFirst){
                                    initTable(clazzId);
                                    isFirst = false;
                                }else{
                                    search($('#searchForm').serializeObject())
                                }
                                getClzAndCourseByclzId(clazzId);
                            }else if(obj.data.field == 'subject'){
                                var subject = obj.data;
                                subjectId = subject.id
                                getClzAndCourseBySubject(subject.id);
                                $('.nav2').text(subject.title);
                                $('.nav3').text('');
                            } else{
                                var academy = obj.data;
                                $('.nav1').text(academy.title);
                                $('.nav2').text('');
                                $('.nav3').text('');
                            }
                        }
                    })
                }
            })
        }

        // 更新、新增
        function update(param, flag) {

            var url = flag == 'add' ? '/ssms/exam/add' : '/ssms/exam/update';
            $.post(url,param,function (res) {
                if (res.code == 200) {
                    reloadTable();
                    if (layerIdx) layer.close(layerIdx);
                } else {
                    layer.msg(res.msg, {icon: 5, time: 2000})
                }
            })
        }

        // 删除
        function remove(data) {
            $.post('/ssms/exam/delete',{id: data.id},function (res) {
                if (res.code == 200) {
                    reloadTable();
                    layer.msg('删除成功', {icon: 6, time: 1000})
                } else {
                    layer.msg(res.msg, {icon: 5, time: 1000})
                }
            })
        }

        function showDialog(exam) {
            layerIdx = layer.open({
                type: 1,
                area: ['500px', '500px'],
                title: '编辑',
                btn: ['提交'],
                content: $('#dialogHtml').html(),
                success:function(){
                    initDialogForm(exam);
                },
                yes: function () {
                    // 弹窗的确定按钮监听
                    $('#dialogBtn').click();
                }
            });
        }

        // 获取对应专业的所有班级、科目
        function getClzAndCourseByclzId(clazzId) {
            var sbjId,sbjName,clazzName;
            var flag = true

            for (var i = 0; i < treeArr.length && flag; i++) {
                var acaChilds = treeArr[i].children;
                if(acaChilds == undefined) continue;

                for (var j = 0; j < acaChilds.length && flag; j++) {
                    var sbjChilds = acaChilds[j].children;
                    if(sbjChilds == undefined) continue;

                    for (var k = 0; k < sbjChilds.length; k++) {
                        var clazz = sbjChilds[k];
                        if(clazzId == clazz.id){
                            sbjId = acaChilds[j].id
                            sbjName = acaChilds[j].title
                            clazzName = clazz.title;
                            flag = false;
                            break;
                        }
                    }
                }
            }

            console.log(sbjId,sbjName,clazzName)
            $('.nav3').text(clazzName);
            $('.nav2').text(sbjName);
            subjectId = sbjId
            getClzAndCourseBySubject(sbjId)
        }

        function getClzAndCourseBySubject(sbjId) {
            // 获取班级
            $.get('/ssms/clazz/all/'+sbjId,function (res) {
                if(res.code == 200){
                    clazzArr = res.data
                }
            })

            // 获取专业的所有科目
            $.get('/ssms/course/all/'+sbjId,function (res) {
                if(res.code == 200){
                    courseArr = res.data
                }
            })
        }

        function initDialogForm(exam) {
            var nowTime=new Date();
            var minTime='00:00:00',maxTime='23:59:59';
            if(exam){ // 编辑打开是也需要设置时间限制
                minTime = exam.startTime+':00'
                maxTime = exam.endTime+':00'
            }

            laydate.render({
                elem: '#examDate',
                format: 'yyyy-MM-dd',
                min:'nowTime'
            });
            var startTime = laydate.render({
                elem: '#startTime',
                type: 'time',
                format: 'HH:mm',
                max:maxTime,
                done:function (value,date) {
                    endTime.config.min={
                        year:date.year,
                        month:date.month-1,//关键
                        date:date.date,
                        hours:date.hours,
                        minutes:date.minutes,
                    }
                }
            });
            var endTime = laydate.render({
                elem: '#endTime',
                type: 'time',
                format: 'HH:mm',
                min: minTime,
                done:function (value,date) {
                    startTime.config.max={
                        year:date.year,
                        month:date.month-1,//关键
                        date:date.date,
                        hours:date.hours,
                        minutes:date.minutes,
                    };

                    // if($('#startTime').val() >= value){
                    //     layer.msg('结束时间必须晚于开始时间', {icon: 7, time: 1500})
                    //     endTime.config.value = ''
                    // }
                    // console.log($('#startTime').val(),value)
                }
            });

            $.each(clazzArr, function (index, item) {
                $('#clazz').append(new Option(item.clazzName, item.id));
            });
            $.each(courseArr, function (index, item) {
                $('#course').append(new Option(item.courseName, item.id));
            });
            form.render("select"); // 重载表单的select

            // 如果是编辑时，初始化弹窗的输入框
            if (exam) {
                form.val("dialog-form", exam)
            }
            form.render()
        }

        // 初始化表格
        function initTable(clazzId) {

            table.render({
                elem: '#exam'
                , url: '/ssms/exam/list'
                , where:{clazzId:clazzId}
                , cols: [[
                    {type: 'numbers', width: 80}
                    , {field: 'clazzName',width: 150, title: '班名'}
                    , {field: 'courseName',width: 200, title: '科目'}
                    , {field: 'examDate',width: 150, title: '考试日期'}
                    , {field: 'startTime',width: 150, title: '开始时间'}
                    , {field: 'endTime',width: 150, title: '结束时间'}
                    , {field: 'address', title: '地点'}
                    // , {field: 'subject', title: '专业',templet:'<div>{{d.subject.subjectName}}</div>'}
                    , {title: '操作', toolbar: '#toolbar', width: 150}
                ]]
                , page: true
            });
        }

        // 表格搜索
        function search(fieldObj) {
            console.log(fieldObj)
            fieldObj.clazzId = clazzId
            table.reload('exam', {
                url: '/ssms/exam/list'
                , where: fieldObj
                , page: {
                    curr: 1
                }
            });
        }
        // 重新加载
        function reloadTable() {
            table.reload('exam', {
                url: '/ssms/exam/list',
            });
        }
    });
</script>
</body>
</html>